/**
 * Copyright (c) 2009  Collaborative Development Group, C.S. Dept., University of Bari
 *
 * All rights reserved. This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License v1.0  which accompanies this distribution, and is 
 * available at http://www.eclipse.org/legal/epl-v10.html
 */
package it.uniba.di.cdg.jtalk.core;

import it.uniba.di.cdg.jtalk.core.events.LoginSuccessfulEvent;
import it.uniba.di.cdg.jtalk.core.gmail.GMail;
import it.uniba.di.cdg.penelope.events.IEventHelper;
import net.jcip.annotations.ThreadSafe;

import org.eclipse.ecf.core.ContainerConnectException;
import org.eclipse.ecf.core.IContainer;
import org.eclipse.ecf.core.identity.ID;
import org.eclipse.ecf.core.identity.IDFactory;
import org.eclipse.ecf.core.security.ConnectContextFactory;
import org.eclipse.ecf.core.security.IConnectContext;
import org.osgi.service.log.LogService;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import static org.osgi.service.log.LogService.*;


/**
 * Handles the user session. 
 */
@Singleton @ThreadSafe
public class UserSession implements IUserSession {
	private final IContainer container;
	private final LogService logger;
	
	private boolean isLoggedIn;
	
	private final IEventHelper eventHelper;

	/**
	 * @param containerProvider
	 */
	@Inject
	public UserSession( @GMail IContainer container, LogService logger, IEventHelper eventHelper ) {
		super();
		this.container = container;
		this.logger = logger;
		this.eventHelper = eventHelper;
	}

	/* (non-Javadoc)
	 * @see it.uniba.di.cdg.jtalk.core.IAccount#logIn(java.lang.String, java.lang.String)
	 */
	@Override
	public synchronized void logIn( String userId, String password ) {
		if (isLoggedIn()) {
			logger.log( LOG_ERROR, "Already logged in!" );
		}
		isLoggedIn = false;
		try {
			ID id = IDFactory.getDefault().createID( container.getConnectNamespace(), userId );
			IConnectContext connectContext = ConnectContextFactory.createPasswordConnectContext( password );
			container.connect( id, connectContext );
			isLoggedIn = true;
			
			eventHelper.fire( new LoginSuccessfulEvent() );
		} catch (ContainerConnectException e) {
			logger.log( LOG_ERROR, e.getMessage() );
			throw new LoginFailedException( e.getCause() );
		}
	}
	
	/* (non-Javadoc)
	 * @see it.uniba.di.cdg.jtalk.core.IAccount#logOff()
	 */
	@Override
	public synchronized void logOff() {
		if (isLoggedIn() && container != null) {
			container.disconnect();		
			isLoggedIn = false;
		}
	}

	/* (non-Javadoc)
	 * @see it.uniba.di.cdg.jtalk.core.IAccount#isLoggedin()
	 */
	@Override
	public boolean isLoggedIn() {
		return isLoggedIn;
	}
}
